#define _CRT_SECURE_NO_WARNINGS 1
#include "SList.h"

SLTNode* SLTBuyNode(SLTDataType s)
{
	SLTNode* node = (SLTNode*)malloc(sizeof(SLTNode));
	if (node == NULL)
	{
		perror("malloc");
		return 0;
	}
	node->data = s;
	node->next = NULL;
	return node;
}

void SLTPrint(SLTNode* phead)
{
	SLTNode* pcur = phead;
	while (pcur != NULL)
	{
		printf("%d -> ", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}
void SLTDesTory(SLTNode** pphead)
{
	SLTNode* pcur = *pphead;
	while (pcur != NULL)
	{
		SLTNode* next = pcur->next;
		pcur->data = 0;
		free(pcur);
		pcur = next;
	}
	*pphead = NULL;
}
void SLTPushBack(SLTNode** pphead,SLTDataType s)
{
	assert(pphead);
	SLTNode* pcur = *pphead;
	SLTNode* newNode = SLTBuyNode(s);
	if (pcur == NULL)
	{
		pcur = newNode;
	}
	else
	{
		while (pcur->next)
		{
			pcur = pcur->next;
		}
		pcur->next = newNode;
	}
}

void SLTPopBack(SLTNode** pphead)
{
	assert(pphead && *pphead);
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLTNode* pcur = *pphead;
		SLTNode* prev = NULL;
		while (pcur->next)
		{
			prev = pcur;
			pcur = pcur->next;
		}
		prev->next = NULL;
		free(pcur);
		pcur = NULL;
	}
}
void SLTPushFront(SLTNode** pphead, SLTDataType s)
{
	assert(pphead);
	SLTNode* newNode = SLTBuyNode(s);
	newNode->next = *pphead;
	*pphead = newNode;
}
void SLTPopFront(SLTNode** pphead)
{
	assert(*pphead && pphead);
	SLTNode* next = (*pphead)->next;
	free(*pphead);
	*pphead = next;
}
SLTNode* SLTFind(SLTNode* pphead, SLTDataType s)
{
	SLTNode* pcur = pphead;
	while (pcur)
	{
		if (pcur->data == s)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}
void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType s)
{
	assert(pphead && pos);
	if (pos == *pphead)
	{
		SLTPushFront(pphead, s);
	}
	else
	{
		SLTNode* pcur = *pphead;
		SLTNode* newNode = SLTBuyNode(s);
		while (pcur->next != pos)
		{
			pcur = pcur->next;
		}
		newNode->next = pos;
		pcur->next = newNode;
	}
}

void SLTInsertAfter(SLTNode* pos, SLTDataType s)
{
	assert(pos);
	SLTNode* newnode = SLTBuyNode(s);
	newnode->next = pos->next;
	pos->next = newnode;
}

void SLTErease(SLTNode** pphead, SLTNode* pos)
{
	assert(pphead && pos);
	if (*pphead == pos)
	{
		SLTPopFront(pphead);
	}
	else
	{
		SLTNode* pcur = *pphead;
		while (pcur->next != pos)
		{
			pcur = pcur->next;
		}
		pcur->next = pos->next;
		free(pos);
		pos = NULL;
	}
}

void SLTEreaseAfter(SLTNode* pos)
{
	assert(pos && pos->next);
	SLTNode* prev = pos->next;
	pos->next = prev->next;
	free(prev);
	prev = NULL;
}






